package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.ContactAddActivity;
import jp.co.sharp.android.parents.kidsguard.activity.edit.ContactsActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.DeviceSelectorAdaptor;
import jp.co.sharp.android.parents.kidsguard.activity.setting.dialog.OkaeriNotificationDlg;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.DeviceListDto;
import jp.co.sharp.android.parents.kidsguard.dto.OkaeriNotificationDto;
import jp.co.sharp.android.parents.kidsguard.dto.WifiListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class DeviceSelectorActivity extends AppCompatActivity {
    public ParentBleTransfer mParentBleTransfer;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private boolean mScreenOperate = false;
    private KidInfoEntity mKidInfoEntity;
    private int mViewProcess = 0;
    private App mApp;
    private ListView mListView;
    private List<WifiListDto> mWifiList = new ArrayList<WifiListDto>();
    private Integer mTag;
    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private final static int SUCCESS_CODE = 500;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(this.TAG, "DeviceSelectorActivity_onCreate");
        setContentView(R.layout.activity_device_selector);

        Intent intent = getIntent();
        mTag = intent.getIntExtra("position", -1);

        mApp = (App) getApplication();
        initReceiver();
        initListener();
        refresh();
        mListView = (ListView) findViewById(R.id.wifiList);
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        showDialog();
        new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
    }

    public void showDialog(){
        // 検索中...
        String pDlgMsg = "検索中..";
        mDealWithWaitingDlg = new DealWithWaitingDlg(DeviceSelectorActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, true);
        mDealWithWaitingDlg.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PowerSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
//                String message = "編集を再開しています...";
//                mDealWithWaitingDlg = new DealWithWaitingDlg(DeviceSelectorActivity.this, R.style.commonDlg, message, false);
//                mDealWithWaitingDlg.show();
//                mScreenOperate = true;
//                mViewProcess = Constants.SEND_KID_IS_USING;
//            new BusinessThread(Constants.SEND_KID_IS_USING,
//                    mParentBleTransfer,
//                    mKidInfoEntity,
//                    null,
//                    PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
//                // ブロードキャストの再登録
//                unregisterReceiver(systemReceiver);
//                initReceiver();
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
//            mUnReceiver = false;
        }
    }

    @Override
    protected void onStop() {
//        super.onStop();
        Log.i(this.TAG, "DeviceSelectorActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try{
                    unregisterReceiver(receiver);
                }catch (IllegalArgumentException e){
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        Log.i(this.TAG, "DeviceSelectorActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();

    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG, "DeviceSelectorActivity_onBackPressed");
        initListener();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "DeviceSelectorActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    public void initListener() {
        Log.i(this.TAG, "DeviceSelectorActivity_back");
        ImageView imageView = findViewById(R.id.back);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(DeviceSelectorActivity.this,OkaeriSettingActivity.class);
//                startActivity(intent);
                backView();

            }
        });
    }

    public void backView() {
        setResult(SUCCESS_CODE);
        mPageJumpFlag=true;
        finish();
    }

    /*
     *refresh
     */
    public void refresh() {
        Log.i(this.TAG, "DeviceSelectorActivity_refresh");
        ImageView imageView = findViewById(R.id.refresh);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
                new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
            }
        });
    }


    public void initReceiver() {
        Log.i(this.TAG, "DeviceSelectorActivity_initReceiver");

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    public JSONObject getInitData() {
        Log.i(this.TAG, "DeviceSelectorActivity_getInitData");
        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject.put("method", RequestMethodConstants.METHOD_GET_WIFI_LIST);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }

    public void setAdaptor() {
        Log.i(this.TAG, "DeviceSelectorActivity_setAdaptor");
        mListView.setAdapter(new DeviceSelectorAdaptor(DeviceSelectorActivity.this, R.layout.activity_device__selector__item, mWifiList,
                new DeviceSelectorAdaptor.OnClickItemListenter() {
                    @Override
                    public void chooseItemClick(int position, View view) {
                        WifiListDto wifiList = mWifiList.get(position);
                        OkaeriNotificationDlg okaeriNotificationDlg = new OkaeriNotificationDlg(DeviceSelectorActivity.this,"ID:"+wifiList.getBssid(),wifiList.getWifiId());
                        okaeriNotificationDlg.show();
                        okaeriNotificationDlg.setOkaeriNameSetListener(new OkaeriNotificationDlg.OkaeriNameSetListener() {
                            @Override
                            public void OkaeriNameSet(String name) {
                                mWifiList.get(position).setWifiId(name);
                                Intent intent = new Intent();
                                intent.putExtra("name", name);
                                intent.putExtra("id",mWifiList.get(position).getBssid());
                                intent.putExtra("position", mTag);
                                setResult(200, intent);
                                mPageJumpFlag=true;
                                finish();
                            }
                        });
                    }
                }));
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                    }

                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
//                            String message = "編集を再開しています...";
//                            mDealWithWaitingDlg = new DealWithWaitingDlg(DeviceSelectorActivity.this, R.style.commonDlg, message, false);
//                            mDealWithWaitingDlg.show();
//                            mScreenOperate = true;
//                            mViewProcess = Constants.SEND_KID_IS_USING;
//                            new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
//                            // ブロードキャストの再登録
//                            unregisterReceiver(systemReceiver);
//                            initReceiver();
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }

                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
                    }

                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);

                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(DeviceSelectorActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(DeviceSelectorActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(DeviceSelectorActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "DeviceSelectorActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (!mScreenOperate) {
                                    new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                                    mDealWithWaitingDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    DeviceSelectorActivity.this.finish();
                                }
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);

                    if (RequestMethodConstants.METHOD_GET_WIFI_LIST.equals(jsonObject.getString("method"))) {
                        mDealWithWaitingDlg.dismiss();
                        //setWifiList
                        setWifiList(jsonObject);
                        //setAdaptor
                        setAdaptor();
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                            //send enter
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERTAL_PERSONAL_ALARM_SETTING, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(DeviceSelectorActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    DeviceSelectorActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (Constants.ON_SYNC_RESULT.equals(jsonObject.getString("result"))) {
                            // ページジャンプ
                            mPageJumpFlag = true;
                            //c
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(DeviceSelectorActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                mPageJumpFlag=true;
                                Intent intent1 = new Intent(DeviceSelectorActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    };

    public void setWifiList(JSONObject jsonObject) throws Exception {
        mWifiList.clear();
        int length = jsonObject.getJSONArray("data").length();
        for (int i = 0; i < length; i++) {
            JSONObject data = (JSONObject) jsonObject.getJSONArray("data").get(i);
            String wifiId = data.getString("wifiId");
            WifiListDto wifiListDto = new WifiListDto();
            wifiListDto.setWifiId(wifiId);
            wifiListDto.setBssid(data.getString("bssid"));
            mWifiList.add(wifiListDto);
        }
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(DeviceSelectorActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };
}
